package com.bestv.c2.handler;

import com.bestv.dao.helper.JDBCHelper;
import com.bestv.utils.UpdateTime;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Henry on 14-7-16.
 */
public class SyncHandler extends Handler {
    private String[] sqls;
    private String exportFilePrefix;
    private UpdateTime updateTime;

    public void handle() throws IOException, ParseException {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateTime = df.format(new Date());

        File output = new File(outputPath);
        exportFile = new File(output, String.format("%s_%s.csv", exportFilePrefix, dateTime));
        FileWriter file = new FileWriter(exportFile);
        BufferedWriter out = new BufferedWriter(file);

        Connection conn = null;
        String time = updateTime.getProperty(exportFilePrefix);
        Date start = df.parse(time);
        boolean firstTime = true;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            for (String sql : sqls) {
                conn = dataSource.getConnection();
                pstmt = conn.prepareStatement(sql);
                pstmt.setDate(1, new java.sql.Date(start.getTime()));
                rs = pstmt.executeQuery();
                if (firstTime) {
                    exportHead(rs, out);
                    firstTime = false;
                }
                exportData(rs, out);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCHelper.close(rs);
            JDBCHelper.close(pstmt);
            JDBCHelper.close(conn);

        }
        updateTime.setProperty(exportFilePrefix, dateTime);
        out.close();
    }

    public String[] getSqls() {
        return sqls;
    }

    public void setSqls(String[] sqls) {
        this.sqls = sqls;
    }

    public String getExportFilePrefix() {
        return exportFilePrefix;
    }

    public void setExportFilePrefix(String exportFilePrefix) {
        this.exportFilePrefix = exportFilePrefix;
    }

    public UpdateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(UpdateTime updateTime) {
        this.updateTime = updateTime;
    }
}
